package dao;

import dto.Student;
import handler.MyHandler;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author NDH SessionID: Bp7GS6um2nH7;
 */
public class StudentDAO {

    public ArrayList<Student> listS;

    public StudentDAO() {
        listS = readAll();
    }

    public ArrayList<Student> readAll() {
        try {
            SAXParserFactory sFac = SAXParserFactory.newInstance();
            SAXParser par = sFac.newSAXParser();
            MyHandler handler = new MyHandler();
            try {
                par.parse(new File("student.xml"), handler);
                listS = handler.listS;
                return listS;
            } catch (IOException ex) {
                Logger.getLogger(StudentDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
            return null;
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(StudentDAO.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(StudentDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;

    }

    public Student readByID(int id) {
        readAll();
        for (Student student : listS) {
            if (student.getCode() == id) {
                return student;
            }
        }
        return null;
    }

    public void create(Student st) {
        if (readByID(st.getCode()) != null) {
            update(st);
        } else {
            listS.add(st);
        }
        writeFile();
    }

    public int update(Student st) {
        readAll();
        for (Student student : listS) {
            if (student.getCode() == st.getCode()) {
                student.setName(st.getName());
                student.setEmail(st.getEmail());
                writeFile();
                return 1;
            }
        }
        return 0;
    }

    public int delete(int id) {
        readAll();
        for (Student student : listS) {
            if (student.getCode() == id) {
                listS.remove(student);
                return 1;
            }
        }
        return 0;
    }

//     public int deleteTreeWalk(int id){
//         Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
//         doc.
//    }
    public void writeFile() {
        try {
            DocumentBuilderFactory docFac = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFac.newDocumentBuilder();
            org.w3c.dom.Document doc = docBuilder.newDocument();
            Element root = doc.createElement("studentlist");
            doc.appendChild(root);

            for (Student student : listS) {
                Element stu = doc.createElement("student");
                root.appendChild(stu);
                Element eCode = doc.createElement("code");
                eCode.appendChild(doc.createTextNode(String.valueOf(student.getCode())));
                Element eName = doc.createElement("name");
                eName.appendChild(doc.createTextNode(student.getName()));
                Element eMail = doc.createElement("email");
                eMail.appendChild(doc.createTextNode(student.getEmail()));
                //
                stu.appendChild(eCode);
                stu.appendChild(eName);
                stu.appendChild(eMail);
                //Write
                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = null;
                try {
                    transformer = transformerFactory.newTransformer();
                } catch (TransformerConfigurationException ex) {
                    Logger.getLogger(StudentDAO.class.getName()).log(Level.SEVERE, null, ex);
                }

                DOMSource source = new DOMSource(doc);
                //output
                StreamResult result = new StreamResult(new File("student.xml"));
                try {
                    transformer.transform(source, result);
                } catch (TransformerException ex) {
                    Logger.getLogger(StudentDAO.class.getName()).log(Level.SEVERE, null, ex);
                }
                System.out.println("File save");
            }
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(StudentDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    void writeFile2(ArrayList<Student> list, String fileName) {
        try {
            Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

            Element root = doc.createElement("studentlist");
            doc.appendChild(root);
            for (Student stu : list) {
                Element stuNode = doc.createElement("student");
                Attr aCode = doc.createAttribute("code");
                aCode.setTextContent(String.valueOf(stu.getCode()));
                Node nName = doc.createElement("name");
                nName.setTextContent(stu.getName());
                Node nEmail = doc.createElement("email");
                nEmail.setTextContent(stu.getEmail());
                //append to student
                stuNode.setAttribute("code", String.valueOf(stu.getCode()));
                stuNode.appendChild(nName);
                stuNode.appendChild(nEmail);
                //appent to roor
                root.appendChild(stuNode);
            }

            Transformer transformer = null;
            try {
                transformer = TransformerFactory.newInstance().newTransformer();
            } catch (TransformerConfigurationException ex) {
                Logger.getLogger(StudentDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
            DOMSource domSource = new DOMSource(doc);
            StreamResult streamResult = new StreamResult(new File(fileName));
            try {
                transformer.transform(domSource, streamResult);
                System.out.println("File save successed!");
            } catch (TransformerException ex) {
                Logger.getLogger(StudentDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(StudentDAO.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public static void main(String[] args) {
        StudentDAO dao = new StudentDAO();
        dao.writeFile2(dao.readAll(), "lemon.xml");
    }
}
